﻿using UnityEngine;

namespace Super
{
	/// <summary>
	/// 非play时，awake不会执行
	/// Instantiate创建对象会立即执行上面的Awake方法
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public class BaseSingle<T> : MonoBehaviour where T : BaseSingle<T>
	{
		private static T ins;
		public static T Ins
		{
			get
			{
				if (ins == null)
				{
					ins = FindObjectOfType<T>() ?? CreateInstance();
					ins.Init();
				}

				return ins;
			}
		}

		public bool isInit = false;
		private void Awake()
		{
			if (ins == null)
			{
				ins = this as T;
				ins.Init();
			}
			else if (ins != this)
			{
				Destroy(this);
			}
		}
		
		public void Init()
		{
		    if (isInit) return;
		    isInit = true;
		    OnInit();
		}

		public virtual void OnInit()
		{

		}

		private static T CreateInstance()
		{
			Transform parent = FWRefManager.Ins.ManagerBoxTf;
			string addr = (string)typeof(T).GetField("addr")?.GetValue(null);
			GameObject go;
			
			if (string.IsNullOrEmpty(addr))
			{
				go = new GameObject(typeof(T).Name);
				go.transform.SetParent(parent);
				go.AddComponent<T>();
			}
			else
			{
				GameObject prefab = AssetUtil.LoadAsset<GameObject>(addr);
				go = GameObject.Instantiate(prefab, parent);
			}
			
			go.transform.position = Vector3.zero;
			go.name = typeof(T).Name;
			return go.GetComponent<T>();
		}

		public static bool CheckIfNotExist()
		{
			return ins == null;
		}
	}

}
